/**         .----.
*       _.'__    `.
*   .--($)($$)---/#\
* .' @          /###\
* :         ,   #####
*  `-..__.-' _.-\###/
*        `;_:    `"'
*      .'"""""`.
*     /,     ,\\
*    //  !BUG  \\
*    `-._______.-'
*    ___`. | .'___
*   (______|______)
*
* jquery.lightbox-JS
* @author kwun
* @email 527565073@qq.com
*/
+(function($){
    var Lightbox = function(settings){
        var elem = this;
        this.settings = {
            speed:500
        }
        $.extend(true,this.settings,settings || {});
        
        //创建弹出层和遮罩层
        this.popupMask = $('<div id="J-lightbox-mask">');
        this.popupWin  = $('<div id="J-lightbox-popup">');

        //保存BODY
        this.bodyNode  = $(document.body);
        this.readerDom();

        this.picViewArea    = this.popupWin.find('div.lightbox-pic-view');//图片预览区域
        this.popupPic       = this.popupWin.find('img.lightbox-image');//图片
        this.picCaptionArea = this.popupWin.find('div.lightbox-pic-caption');//图片描述区域
        this.prevBtn        = this.popupWin.find('span.lightbox-prev-btn');//向前切换
        this.nextBtn        = this.popupWin.find('span.lightbox-next-btn');//向后切换
        this.captionText    = this.popupWin.find('p.lightbox-pic-desc');//图片描述区域
        this.currentIndex   = this.popupWin.find('span.lightbox-of-index');//图片索引
        this.rotateLeft     = this.popupWin.find('span.lightbox-rotate-left-btn');//图片转左
        this.rotateRight    = this.popupWin.find('span.lightbox-rotate-right-btn');//图片转右
        this.closeBtn       = this.popupWin.find('span.lightbox-close-btn');//关闭按钮
 

        //准备开放事件委托，获取组数据
        this.groupName = null;
        this.groupData = []; //放置同一组数据
        this.bodyNode.delegate('.js-lightbox,[data-role=lightbox]', 'click', function(event) {
            //阻止事件冒泡
            event.stopPropagation();
            var crtGroupName = $(this).attr('data-group');
            if(crtGroupName != elem.groupName){
                elem.groupName = crtGroupName;
                //根据当前组名获取同一组数据
                elem.getGroup();
            }

            //初始化弹出
            elem.initPopup($(this));
        });

        this.popupMask.click(function(){
            $(this).fadeOut();
            elem.popupWin.fadeOut();
            elem.clear = false;
        });
        this.closeBtn.click(function(){
            elem.popupMask.fadeOut();
            elem.popupWin.fadeOut();
            elem.clear = false;
        })

        //绑定上下切换按钮事件
        this.flag = true;
        this.prevBtn.hover(function(){
            if(!$(this).hasClass('disabled') && elem.groupData.length>1){
                $(this).addClass('lightbox-prev-btn-show');
            }
        },function(){
            if(!$(this).hasClass('disabled') && elem.groupData.length>1){
                $(this).removeClass('lightbox-prev-btn-show');
            }
        }).click(function(e){
            if(!$(this).hasClass('disabled')&&elem.flag){
                elem.flag = false;
                e.stopPropagation();
                elem.goto('prev');
            }
        })
        this.nextBtn.hover(function(){
            if(!$(this).hasClass('disabled') && elem.groupData.length>1){
                $(this).addClass('lightbox-next-btn-show');
            }
        },function(){
            if(!$(this).hasClass('disabled') && elem.groupData.length>1){
                $(this).removeClass('lightbox-next-btn-show');
            }
        }).click(function(e){
            if(!$(this).hasClass('disabled')&&elem.flag){
                elem.flag = false;
                e.stopPropagation();
                elem.goto('next');
            }
        })

        //绑定图片旋转事件
        this.rotateLeft.click(function(){
            elem.rotateImage('left');
        })
        this.rotateRight.click(function(){
            elem.rotateImage('right');
        })

        //判断是否IE6
        this.isIE6 = /MSIE 6.0/gi.test(window.navigator.userAgent);

        //绑定窗口调整事件
        var timer  = null;
        this.clear = false;
        $(window).resize(function(){
            if(elem.clear){
                window.clearTimeout(timer);
                timer = window.setTimeout(function(){
                    elem.loadPicSize(elem.groupData[elem.index].src);
                },500)

                if(elem.isIE6){
                    elem.popupMask.css({
                        width:$(window).width(),
                        height:$(window).height()
                    })
                }

            }
            
        }).keyup(function(event) {
            var keyCode = event.which;
            if(elem.clear){
                if(keyCode == 37 || keyCode == 38){
                    elem.prevBtn.click();
                }else if(keyCode == 39 || keyCode == 40){
                    elem.nextBtn.click();
                }else if(keyCode == 27){
                    elem.closeBtn.click();
                }
            }
        });

        //如果是IE6
        if(this.isIE6){
            $(window).scroll(function(){
                elem.popupMask.css('top',$(window).scrollTop())
            })
        }

    }

    Lightbox.prototype = {
        initPopup:function(currentObj){
            var elem      = this,
                sourceSrc = currentObj.attr('data-source'),
                currentId = currentObj.attr('data-id');

            this.showMaskAndPopup(sourceSrc,currentId);
        },
        goto:function(dir){
            if(dir === 'prev'){
                this.index--
                if(this.index <= 0){
                    this.prevBtn.addClass('disabled').removeClass('lightbox-prev-btn-show');                    
                }
                if(this.index != this.groupData.length-1){
                    this.nextBtn.removeClass('disabled');
                }
                
                var src = this.groupData[this.index].src;
                this.loadPicSize(src);
            }else if(dir === 'next'){
                this.index++
                if(this.index >= this.groupData.length-1){
                    this.nextBtn.addClass('disabled').removeClass('lightbox-next-btn-show');                    
                }
                if(this.index != 0){
                    this.prevBtn.removeClass('disabled');
                }

                var src = this.groupData[this.index].src;
                this.loadPicSize(src);
            }

        },
        showMaskAndPopup:function(sourceSrc,currentId){
            var elem      = this,
                winWidth  = $(window).width(),
                winHeight = $(window).height();

            this.popupPic.hide();
            this.picCaptionArea.hide();

            this.picViewArea.css({
                width:winWidth/2,
                height:winHeight/2
            })
            var viewHeight = winHeight/2+10;
            var topAnimate = (winHeight-viewHeight)/2

            if(this.isIE6){
                var scollTop = $(window).scrollTop();
                this.popupMask.css({
                    width:winWidth,
                    height:winHeight,
                    top:scollTop
                })
            }
            this.popupMask.fadeIn();
            this.popupWin.fadeIn().css({
                width:(winWidth/2)+10,
                height:viewHeight,
                marginLeft:-((winWidth/2)+10)/2,
                top:(this.isIE6?-(viewHeight+scollTop):-viewHeight)
            }).animate({
                top:(this.isIE6?(topAnimate+scollTop):topAnimate)
            },this.settings.speed,function(){
                //加载图片
                elem.loadPicSize(sourceSrc);
            });

            //根据当前点击元素ID获取在当前组别里面的索引    
            this.index = this.getIndexOf(currentId);
            
            var groupDataLength = this.groupData.length;
            if(groupDataLength > 1){
                //this.prevBtn this.nextBtn
                if(this.index === 0){
                    this.prevBtn.addClass('disabled');
                    this.nextBtn.removeClass('disabled');
                }else if(this.index === groupDataLength-1){
                    this.prevBtn.removeClass('disabled');
                    this.nextBtn.addClass('disabled');
                }else{
                    this.prevBtn.removeClass('disabled');
                    this.nextBtn.removeClass('disabled');
                }
            }else{
                this.prevBtn.addClass('disabled');
                this.nextBtn.addClass('disabled');
            }
        },
        loadPicSize:function(sourceSrc){
            var elem = this;
            this.popupPic.css({
                width:"auto",
                height:"auto"
            }).hide();
            this.picCaptionArea.hide();
            this.preLoadImg(sourceSrc,function(){
                elem.popupPic.attr('src',sourceSrc)
                var picWidth  = elem.popupPic.width(),
                    picHeight = elem.popupPic.height();

                elem.changePic(picWidth,picHeight);
            })
        },
        changePic:function(width,height){
            var elem        = this,
                winWidth    = $(window).width(),
                winHeight   = $(window).height();
            //如果图片的宽高大于浏览器视口的宽高比例，是否溢出
            var scale = Math.min(winWidth/(width+10),winHeight/(height+10),1);
            width     = width*scale;
            height    = height*scale;

            this.picViewArea.animate({
                width:width-10,
                height:height-10
            },this.settings.speed);

            var top = (winHeight-height)/2
            if(this.isIE6){
                top += $(window).scrollTop();
            }
            this.popupWin.animate({
                width:width,
                height:height,
                marginLeft:-(width/2),
                top: top
            },this.settings.speed,function(){
                elem.popupPic.css({
                    width:width,
                    height:height
                }).fadeIn();
                elem.picCaptionArea.fadeIn();
                elem.flag  = true;
                elem.clear = true;
            })
            //设置描述文字和当前索引
            this.captionText.text(this.groupData[this.index].caption);
            this.currentIndex.text('当前索引： '+(this.index+1)+' of '+this.groupData.length)
        },
        rotateImage:function(pos){
            /*var elem = this;
            var img = this.popupPic[0];
            if(!img || !pos) return false;
            var num = img.getAttribute('step');
            if(num== null) num=0; 
            if(pos=='right'){ 
                (num==3)? num=0:num++; 
            }else if(pos=='left'){
                (num==0)? num=3:num--; 
            } 
            img.setAttribute('step',num);
            img.style.visibility = 'hidden';
            var c = document.getElementById('lightbox-canvas');
            if(c== null){ 
                img.style.visibility = 'hidden'; 
                img.style.position = 'absolute'; 
                c = document.createElement('canvas'); 
                c.setAttribute("id",'lightbox-canvas'); 
                img.parentNode.appendChild(c); 
            }else{
                c.style.visibility = "visible";
            }
            var canvasContext = c.getContext('2d'); 
            switch(num) { 
                default : 
                case 0 :
                    c.setAttribute('width', img.width); 
                    c.setAttribute('height', img.height); 
                    canvasContext.rotate(0 * Math.PI / 180); 
                    canvasContext.drawImage(img, 0, 0);
                    elem.changePic(img.width,img.height)
                    break; 
                case 1 :
                    c.setAttribute('width', img.height); 
                    c.setAttribute('height', img.width); 
                    canvasContext.rotate(90 * Math.PI / 180); 
                    canvasContext.drawImage(img, 0, -img.height);
                    elem.changePic(img.height,img.width)
                    break; 
                case 2 :
                    c.setAttribute('width', img.width); 
                    c.setAttribute('height', img.height);
                    canvasContext.rotate(180 * Math.PI / 180); 
                    canvasContext.drawImage(img, -img.width, -img.height);
                    elem.changePic(img.width,img.height)
                    break; 
                case 3 :
                    c.setAttribute('width', img.height); 
                    c.setAttribute('height', img.width); 
                    canvasContext.rotate(270 * Math.PI / 180); 
                    canvasContext.drawImage(img, -img.width, 0); 
                    elem.changePic(img.height,img.width)
                    break; 
            }*/
        },
        preLoadImg:function(src,callback){
            var img = new Image();
            if(!!window.ActiveXObject){
                img.onreadystatechange = function(){
                    if(this.readyState == 'complete'){
                        callback();
                    }
                }
            }else{
                img.onload = function(){
                    callback();
                }
            }
            img.src = src;
        },
        getIndexOf:function(currentId){
            var elem  = this,
                index = 0;

            $(this.groupData).each(function(i){
                index = i;
                if(this.id === currentId){
                    return false;
                }
            })
            return index;
        },
        getGroup:function(){
            var elem = this;
            //根据当前的组别名称获取页面中所有相同组别的数据
            var groupList = this.bodyNode.find('*[data-group='+this.groupName+']');
            //清空数组数据
            elem.groupData.length = 0;
            groupList.each(function(){
                elem.groupData.push({
                    src:$(this).attr('data-source'),
                    id:$(this).attr('data-id'),
                    caption:$(this).attr('data-caption')
                })
            })
        },
        readerDom:function(){
            var strDom = '<div class="lightbox-pic-view">'+
                            '<span class="lightbox-btn lightbox-prev-btn"></span>'+
                            '<img class="lightbox-image">'+
                            '<span class="lightbox-btn lightbox-next-btn"></span>'+
                        '</div>'+
                        '<div class="lightbox-pic-caption">'+
                            '<div class="lightbox-caption-area">'+
                                '<p class="lightbox-pic-desc"></p>'+
                                '<span class="lightbox-of-index">当前索引：0 of 0</span>'+
                            '</div>'+
                            '<div class="lightbox-btn-area">'+
                                '<span class="lightbox-rotate-btn">'+
                                    '<span class="lightbox-rotate-left-btn" title="向左旋转90°"></span>'+
                                    '<span class="lightbox-rotate-right-btn" title="向右旋转90°"></span>'+
                                '</span>'+
                                '<span class="lightbox-close-btn">×</span>'+
                            '</div>'+
                        '</div>'

            //插入到this.popupWin
            this.popupWin.html(strDom);
            //渲染剩余的Dom，并且插入到body
            this.bodyNode.append(this.popupMask);
            this.bodyNode.append(this.popupWin);            
        }
    }
    
    window["Lightbox"] = Lightbox;
})(jQuery)